package cn.iocoder.yudao.module.cmt.service.course;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import cn.iocoder.yudao.module.cmt.controller.admin.course.vo.*;
import cn.iocoder.yudao.module.cmt.dal.dataobject.course.CourseCategoryDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.cmt.dal.mysql.course.CourseCategoryMapper;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.cmt.enums.ErrorCodeConstants.*;

@Service
@Validated
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public Long createCourseCategory(CourseCategorySaveReqVO createReqVO) {
        CourseCategoryDO courseCategory = BeanUtils.toBean(createReqVO, CourseCategoryDO.class);
        courseCategoryMapper.insert(courseCategory);
        return courseCategory.getId();
    }

    @Override
    public void updateCourseCategory(CourseCategorySaveReqVO updateReqVO) {
        validateCourseCategoryExists(updateReqVO.getId());
        CourseCategoryDO updateObj = BeanUtils.toBean(updateReqVO, CourseCategoryDO.class);
        courseCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteCourseCategory(Long id) {
        validateCourseCategoryExists(id);
        courseCategoryMapper.deleteById(id);
    }

    private void validateCourseCategoryExists(Long id) {
        if (courseCategoryMapper.selectById(id) == null) {
            throw exception(COURSE_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public CourseCategoryDO getCourseCategory(Long id) {
        return courseCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<CourseCategoryDO> getCourseCategoryPage(CourseCategoryPageReqVO pageReqVO) {
        return courseCategoryMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCourseCategoryListByIds(List<Long> ids) {
        ids.forEach(this::validateCourseCategoryExists);
        courseCategoryMapper.deleteBatchIds(ids);
    }

}
